import { useEffect, useMemo, useState } from 'react'
import { Button, Dialog, Empty, Input, List, NavBar, Toast, Tag, Space } from 'antd-mobile'
import { getUserFaceList, deleteFaceFromUser, deleteUserFromFaceSet } from '../../api/faceRecognition'
import { useNavigate, useSearchParams } from 'react-router-dom'
import './index.css'

function FaceManagePage() {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()

  const [groupIdInput, setGroupIdInput] = useState<string>('user_faces')
  const [userIdInput, setUserIdInput] = useState<string>('')

  const groupId = useMemo(() => searchParams.get('groupId') || groupIdInput, [searchParams, groupIdInput])
  const userId = useMemo(() => searchParams.get('userId') || userIdInput, [searchParams, userIdInput])

  const [loading, setLoading] = useState<boolean>(false)
  const [faces, setFaces] = useState<Array<{ face_token: string; ctime: string }>>([])

  const handleLoad = async () => {
    if (!groupId || !userId) {
      Toast.show({ content: '请填写 groupId 和 userId' })
      return
    }
    setLoading(true)
    const res = await getUserFaceList(groupId, userId)
    setLoading(false)
    if (res.success && res.data) {
      setFaces(res.data.face_list || [])
    } else {
      Toast.show({ content: res.message })
      setFaces([])
    }
  }

  const handleDeleteFace = async (faceToken: string) => {
    const confirm = await Dialog.confirm({ content: `确定删除该人脸吗？\nface_token: ${faceToken}` })
    if (!confirm) return
    const res = await deleteFaceFromUser(groupId, userId, faceToken)
    if (res.success) {
      Toast.show({ content: '删除成功' })
      handleLoad()
    } else {
      Toast.show({ content: res.message })
    }
  }

  const handleDeleteUser = async () => {
    const confirm = await Dialog.confirm({ content: `确定删除该用户在组 ${groupId} 下的所有人脸吗？` })
    if (!confirm) return
    const res = await deleteUserFromFaceSet(groupId, userId)
    if (res.success) {
      Toast.show({ content: '已删除该用户' })
      setFaces([])
    } else {
      Toast.show({ content: res.message })
    }
  }

  useEffect(() => {
    if (searchParams.get('groupId') && searchParams.get('userId')) {
      setGroupIdInput(searchParams.get('groupId') || 'user_faces')
      setUserIdInput(searchParams.get('userId') || '')
      handleLoad()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <div className="face-manage">
      <NavBar onBack={() => navigate(-1)}>人脸库管理</NavBar>

      <div className="fm-body">
        <div className="fm-filters">
          <Input
            placeholder='group_id (如: user_faces 或 wusounian)'
            value={groupIdInput}
            onChange={setGroupIdInput}
          />
          <Input
            placeholder='user_id'
            value={userIdInput}
            onChange={setUserIdInput}
          />
        </div>
        <div className="fm-actions">
          <Button color='primary' loading={loading} onClick={handleLoad}>加载列表</Button>
          <Button color='danger' onClick={handleDeleteUser}>删除该用户</Button>
        </div>

        {faces.length === 0 ? (
          <Empty description='没有人脸数据' />
        ) : (
          <List header={<Space align='center'>
            <Tag color='primary' fill='outline'>共 {faces.length} 张人脸</Tag>
            <span className="fm-subtle">仅展示 face_token 和时间，支持删除</span>
          </Space>}>
            {faces.map((f) => (
              <List.Item
                key={f.face_token}
                description={<span className='fm-ctime'>时间 {f.ctime}</span>}
                extra={<Button size='small' color='danger' onClick={() => handleDeleteFace(f.face_token)}>删除</Button>}
              >
                <div className='fm-token-row'>
                  <span className='fm-token-label'>face_token</span>
                  <span className='fm-token' title={f.face_token}>{f.face_token}</span>
                  <Button size='mini' onClick={() => navigator.clipboard.writeText(f.face_token)}>复制</Button>
                </div>
              </List.Item>
            ))}
          </List>
        )}
      </div>
    </div>
  )
}

export default FaceManagePage


